package hu.ikti.oamadmin.beans.utils;

import java.io.Serializable;
import java.util.Calendar;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

import hu.ikti.oamadmin.beans.BaseBean;
import hu.ikti.oamadmin.types.entities.Bundle;
import hu.ikti.oamadmin.types.entities.ByteCode;
import hu.ikti.oamadmin.types.entities.Resource;

@Name("resourceUtil")
@Scope(ScopeType.SESSION)
public class ResourceUtil extends BaseBean implements Serializable {

	private static final long serialVersionUID = 1L;

	@In(required = false)
	private Bundle bundle;

	public void uploadListener(UploadEvent event) throws Exception {
		bundle = (Bundle) entityManager
				.createQuery(
						"select bundle from Bundle bundle "
								+ "left outer join bundle.resources "
								+ "where bundle.id = :id")
				.setParameter("id", bundle.getId()).getSingleResult();
		UploadItem item = event.getUploadItem();
		String[] parsedFileName = item.getFileName().split("\\.");
		Resource resource = new Resource();
		ByteCode byteCode = new ByteCode();
		byteCode.setBytes(item.getData());
		resource.setByteCode(byteCode);
		resource.setExtension(parsedFileName[parsedFileName.length - 1]);
		resource.setFileName(item.getFileName());
		resource.setUploadTime(Calendar.getInstance().getTime());
		resource.setSize(item.getFileSize());
		bundle.getResources().add(resource);
		entityManager.merge(bundle);
	}
}
